/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ContaDialog.java
 *
 * Created on Jan 14, 2011, 10:38:02 AM
 */
package br.com.tbp.gui.financeiro;

import br.com.tbp.controle.ControleConta;
import br.com.tbp.exception.InputValidationException;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.model.domain.financeiro.CondicaoConta;
import br.com.tbp.model.domain.financeiro.Conta;
import br.com.tbp.model.domain.financeiro.TipoConta;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import um.filteredtext.number.CurrencyNumberAdapter;

/**
 *
 * @author Diego Freire
 */
public class ContaDialog extends javax.swing.JDialog {

    private boolean novaConta;
    private Conta conta;
    private boolean refresh = false;
    private CurrencyNumberAdapter caCurrency;

    public ContaDialog(java.awt.Frame parent, String name, boolean modal) {
        super(parent, name, modal);
        initComponents();
        setLocationRelativeTo(null);
        configTextFieldsDeDinheiro();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        contentPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();
        jPanel10 = new javax.swing.JPanel();
        baixarLink = new org.jdesktop.swingx.JXHyperlink();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        idTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        descricaoTextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        obsTextArea = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        tipoComboBox = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        dataTextField = new org.jdesktop.swingx.JXDatePicker();
        jLabel6 = new javax.swing.JLabel();
        valorTextField = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        condicaoComboBox = new javax.swing.JComboBox();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        novoButton = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        salvarButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        contentPanel.setLayout(new java.awt.BorderLayout());

        jPanel1.setPreferredSize(new java.awt.Dimension(400, 40));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel9.setBackground(new java.awt.Color(255, 255, 255));
        jPanel9.setPreferredSize(new java.awt.Dimension(103, 74));
        jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/fornecedor.png"))); // NOI18N
        msgLabel.setText("msg");
        jPanel9.add(msgLabel);

        jPanel1.add(jPanel9, java.awt.BorderLayout.CENTER);

        jPanel10.setBackground(new java.awt.Color(255, 255, 255));
        jPanel10.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 1, 1, 1));

        baixarLink.setForeground(new java.awt.Color(0, 153, 0));
        baixarLink.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/lapis_16.png"))); // NOI18N
        baixarLink.setText("dar baixa");
        baixarLink.setToolTipText("Dar baixa...");
        baixarLink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                baixarLinkActionPerformed(evt);
            }
        });
        jPanel10.add(baixarLink);

        jPanel1.add(jPanel10, java.awt.BorderLayout.LINE_END);

        contentPanel.add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info. Básicas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        jLabel1.setText("ID conta:");

        idTextField.setEditable(false);
        idTextField.setFocusable(false);

        jLabel2.setText("Descrição:");

        jLabel3.setText("Observações:");

        obsTextArea.setColumns(20);
        obsTextArea.setLineWrap(true);
        obsTextArea.setRows(5);
        obsTextArea.setText("diária\nsemanal\nmensal\nbimestral\ntrimestral\nsemestral\nanual");
        obsTextArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(obsTextArea);

        jLabel4.setText("Tipo:");

        tipoComboBox.setModel(new DefaultComboBoxModel(TipoConta.values()));

        jLabel5.setText("Data:");

        jLabel6.setText("Valor:");

        jLabel7.setText("Condição:");

        condicaoComboBox.setModel(new DefaultComboBoxModel(CondicaoConta.values()));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(descricaoTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(58, 58, 58)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dataTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(tipoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(condicaoComboBox, 0, 218, Short.MAX_VALUE))
                            .addComponent(valorTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(descricaoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dataTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tipoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addComponent(condicaoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(valorTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(12, 12, 12)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        contentPanel.add(jPanel2, java.awt.BorderLayout.CENTER);

        getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

        jPanel4.setLayout(new java.awt.BorderLayout());

        novoButton.setMnemonic('n');
        novoButton.setText("Nova Conta");
        novoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoButtonActionPerformed(evt);
            }
        });
        jPanel5.add(novoButton);

        jPanel4.add(jPanel5, java.awt.BorderLayout.LINE_START);

        salvarButton.setMnemonic('s');
        salvarButton.setText("Salvar");
        salvarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarButtonActionPerformed(evt);
            }
        });
        jPanel6.add(salvarButton);

        fecharButton.setText("Fechar (ESC)");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });
        jPanel6.add(fecharButton);

        jPanel4.add(jPanel6, java.awt.BorderLayout.LINE_END);

        getContentPane().add(jPanel4, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void novoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoButtonActionPerformed
        setConta(new Conta());
        setNovaConta(true);
}//GEN-LAST:event_novoButtonActionPerformed

    private void salvarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarButtonActionPerformed
        try {
            this.validarEntradaDoUsuario();

            ControleConta controle = new ControleConta();
            Conta c = this.getConta();
            if (isNovaConta()) {
                controle.adicionar(c);
                msgLabel.setText("A conta foi adicionada com sucesso");
                refresh(true);
            } else {
                controle.editar(c);
                msgLabel.setText("Os dados da conta foram editados com sucesso");
                refresh(true);
            }
        } catch (InputValidationException ivex) {
            msgLabel.setText(ivex.getMessage());
            System.out.println(ivex.getMessage());
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
}//GEN-LAST:event_salvarButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        this.dispose();
}//GEN-LAST:event_fecharButtonActionPerformed

    private void baixarLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_baixarLinkActionPerformed
       
}//GEN-LAST:event_baixarLinkActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ContaDialog dialog = new ContaDialog(new javax.swing.JFrame(), "TBP - Conta", true);
                dialog.setConta(new Conta());
                dialog.setNovaConta(true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXHyperlink baixarLink;
    private javax.swing.JComboBox condicaoComboBox;
    private javax.swing.JPanel contentPanel;
    private org.jdesktop.swingx.JXDatePicker dataTextField;
    private javax.swing.JTextField descricaoTextField;
    private javax.swing.JButton fecharButton;
    private javax.swing.JTextField idTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JButton novoButton;
    private javax.swing.JTextArea obsTextArea;
    private javax.swing.JButton salvarButton;
    private javax.swing.JComboBox tipoComboBox;
    private javax.swing.JTextField valorTextField;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>

    public boolean isNovaConta() {
        return novaConta;
    }

    public void setNovaConta(boolean n) {
        this.novaConta = n;
        if (isNovaConta()) {
            msgLabel.setText("Forneça os dados para a nova conta");
        } else {
            msgLabel.setText("Visualização dos dados da conta nº " + this.conta.getId());
        }
        descricaoTextField.requestFocus();
    }

    public Conta getConta() {
        conta.setDescricao(descricaoTextField.getText());
        conta.setData(dataTextField.getDate());
        conta.setTipo((TipoConta) tipoComboBox.getSelectedItem());
        conta.setCondicao((CondicaoConta) condicaoComboBox.getSelectedItem());
        try {
            Number valor = caCurrency.getNumberFormat().parseNumber(valorTextField.getText());
            conta.setValor(new Double(valor.toString()));
        } catch (ParseException pex) {
            System.out.println(pex.getMessage());
        }
        conta.setObs(obsTextArea.getText());
        return conta;
    }

    public void setConta(Conta c) {
        this.conta = c;

        idTextField.setText("" + c.getId());
        descricaoTextField.setText(c.getDescricao());
        dataTextField.setDate(c.getData());
        tipoComboBox.setSelectedItem(c.getTipo());
        condicaoComboBox.setSelectedItem(c.getCondicao());
        if (c.getValor() != null) {
            valorTextField.setText(caCurrency.getNumberFormat().formatNumber(c.getValor()));
        } else {
            valorTextField.setText(null);
        }
        obsTextArea.setText(c.getObs());
        obsTextArea.setCaretPosition(0);
    }

    public void validarEntradaDoUsuario() throws InputValidationException {
        if (descricaoTextField.getText().isEmpty()) {
            descricaoTextField.requestFocus();
            throw new InputValidationException("A descrição deve ser informada");
        }
        if (dataTextField.getDate() == null) {
            dataTextField.requestFocus();
            throw new InputValidationException("A data deve ser informada");
        }
        if (tipoComboBox.getSelectedItem() == null) {
            tipoComboBox.requestFocus();
            throw new InputValidationException("O tipo deve ser selecionado");
        }
        if (valorTextField.getText().isEmpty()) {
            valorTextField.requestFocus();
            throw new InputValidationException("O valor R$ deve ser informado");
        }

    }

    public boolean refresh() {
        return refresh;
    }

    public void refresh(boolean r) {
        this.refresh = r;
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }

    private void configTextFieldsDeDinheiro() {
        caCurrency = new CurrencyNumberAdapter(false);

        valorTextField.addKeyListener(caCurrency);
        valorTextField.addFocusListener(caCurrency);
    }
}
